﻿using System;
using System.Windows.Forms;
using BorgExt.Behaviors;

namespace BorgExt.Forms.Behaviors
{
    public class ComboBoxBinding<T> : Rule<T>
        where T : class
    {
        private readonly ComboBox _comboBox;
        private T _composedItem;
        private int _noUpdate;

        public ComboBoxBinding(ComboBox comboBox)
        {
            _comboBox = comboBox;
            _comboBox.SelectedValueChanged += SelectedValueChanged;
        }

        public override void AddCandidate(T item)
        {
            _comboBox.Items.Add(item);
        }

        public override void Composed(T item)
        {
            _noUpdate++;

            if (_composedItem != null && _composedItem != item)
                OnDecompose(_composedItem);

            _composedItem = item;
            _comboBox.SelectedItem = item;
            _noUpdate--;
        }

        public override void Decomposed(T item)
        {
            _noUpdate++;

            if (_composedItem == item)
                _composedItem = default(T);

            if (_comboBox.SelectedItem == item)
                _comboBox.SelectedItem = null;

            _noUpdate--;
        }

        public override void RemoveCandidate(T item)
        {
            _comboBox.Items.Remove(item);
        }

        private void SelectedValueChanged(object sender, EventArgs e)
        {
            if (_noUpdate > 0)
                return;

            if (_composedItem != null)
                OnDecompose(_composedItem);

            if (_comboBox.SelectedItem != null)
                OnCompose((T)_comboBox.SelectedItem);
        }
    }
}

